<template>
  <el-form
    :model="newUserForm"
    :rules="newUserRules"
    ref="userForm"
    status-icon
    v-loading="loading"
  >
    <el-form-item prop="userface" label="个人头像" label-width="100px">
      <el-upload
        class="upload-item-info"
        :action="userfaceAction"
        :headers="actionData"
        :before-upload="handleBeforeUpload"
        :on-change="handleChange"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        list-type="picture"
        :show-file-list="false"
        :auto-upload="true"
      >
        <el-button size="small" type="primary">选择图片</el-button>
      </el-upload>
      <td-image
        v-model="layerImg"
        :type="submitText < 0 ? 'preview' : 'drag'"
        @remove="removeImg"
      ></td-image>
    </el-form-item>
    <el-form-item prop="realName" label="姓名" label-width="100px">
      <el-input
        :disabled="submitText < 0 ? true : false"
        v-model="newUserForm.realName"
        placeholder="请输入您的姓名"
      ></el-input>
    </el-form-item>
    <el-form-item prop="username" label="用户名" label-width="100px">
      <el-input
        :disabled="submitText < 0 ? true : false"
        v-model="newUserForm.username"
        placeholder="请输入您的用户名"
      ></el-input>
    </el-form-item>
    <el-form-item prop="roleId" label="用户角色" label-width="100px">
      <el-select
        :disabled="submitText < 0 ? true : false"
        v-model="newUserForm.roleId"
        placeholder="请选择用户类型"
      >
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="telPhone" label="联系电话" label-width="100px">
      <el-input
        type="text"
        :disabled="submitText < 0 ? true : false"
        v-model="newUserForm.telPhone"
      ></el-input>
    </el-form-item>
    <el-form-item prop="email" label="个人邮箱" label-width="100px">
      <el-input
        type="text"
        :disabled="submitText < 0 ? true : false"
        v-model="newUserForm.email"
      ></el-input>
    </el-form-item>
    <el-form-item prop="address" label="详细地址" label-width="100px">
      <el-input
        type="text"
        :disabled="submitText < 0 ? true : false"
        v-model="newUserForm.address"
      ></el-input>
    </el-form-item>
    <el-form-item v-if="submitText >= 0" style="text-align: center;">
      <el-button type="danger" class="submit_btn" @click="onCloseUserDialog"
        >取消</el-button
      >
      <el-button type="primary" class="submit_btn" @click="onSubmitUserInfo"
        >提交</el-button
      >
    </el-form-item>
  </el-form>
</template>
<script>
import { userManage, roleManage, uploadFile } from '@/api'
import TdImage from '@/components/TdImage.vue'

var baseUrl = process.env.VUE_APP_BASE_API
const newUserForm = {
  icon: '',
  realName: '',
  username: '',
  roleId: '',
  telPhone: '',
  email: '',
  address: ''
}
export default {
  name: 'form-user',
  componentName: 'formUser',
  components: { TdImage },
  data() {
    const validatorUsername = (rule, value, callback) => {
      if (!/^[A-Za-z0-9\_]{4,20}$/.test(value)) {
        return callback(
          new Error('请输入不少于四位不超过二十位的英文数字用户名')
        )
      } else {
        callback()
      }
    }
    const validataTelPhone = (rule, value, callback) => {
      const phoneReg = /^1[3-9]\d{9}$/
      const telReg = /^([0\+]\d{2,3}-?)?(\d{7,8})$/
      if (value) {
        if (phoneReg.test(value) || telReg.test(value)) {
          callback()
        } else {
          callback(new Error('您的电话号码输入有错误'))
        }
      } else {
        callback()
      }
    }

    const validatorEmail = (rule, value, callback) => {
      const emailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w)*/
      if (value) {
        if (!emailReg.test(value)) {
          callback(new Error('您的邮箱号输入有错误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      loading: false,
      actionData: { Authorization: 'Bearer ' + localStorage.getItem('token') },
      userfaceAction: baseUrl + '/txUpload', // 头像upload
      userfaceUrl: baseUrl, // 头像远端地址
      fileList: [],
      layerImg: [], // 图片显示全路径
      images: null, // 图片显示短路径
      faceIds: null, // 图片id
      options: [], // 角色类型
      newUserForm: { ...newUserForm },
      newUserRules: {
        // 用户编辑 添加检验
        realName: [
          {
            type: 'string',
            required: true,
            message: '请输入您的姓名',
            trigger: 'blur'
          }
        ],
        username: [
          {
            type: 'string',
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          { validator: validatorUsername, trigger: 'blur' }
        ],
        roleId: [
          {
            type: 'string',
            required: true,
            message: '请选择用户角色',
            trigger: 'blur'
          }
        ],
        telPhone: [{ validator: validataTelPhone, trigger: 'blur' }],
        email: [{ validator: validatorEmail, trigger: 'blur' }]
      }
    }
  },
  props: {
    submitText: Number,
    userId: String
  },
  watch: {
    userId(newV, oldV) {
      if (newV) {
        this.getUserInfo()
      } else {
        this.newUserForm = { ...newUserForm }
        this.layerImg = []
      }
    },
    submitText(newV, oldV) {
      if (newV === 0) {
        this.newUserForm = { ...newUserForm }
        this.layerImg = []
      }
    }
  },
  created() {
    if (this.userId) this.getUserInfo()
    this.getRoleList()
  },
  methods: {
    // 获取用户类型
    async getRoleList() {
      this.loading = true
      try {
        const roleRes = await roleManage.getAllRoleList()
        this.options = roleRes.data
        this.loading = false
      } catch {
        this.loading = false
      }
    },
    async getUserInfo() {
      try {
        const res = await userManage.selectUser({ id: this.userId })
        console.log(res.data)
        let imageArr = []
        if (res.data.icon != '') imageArr.push(this.userfaceUrl + res.data.icon)
        this.layerImg = imageArr
        this.newUserForm = res.data
        console.log(res.data)
      } catch {
        this.$message.error({
          message: 'Error'
        })
      }
    },
    // 头像提交
    handleBeforeUpload(file) {
      let fileObj = {
        name: file.name,
        size: file.size,
        status: '开始上传',
        process: 0,
        id: file.uid,
        type: /^image/.test(file.type)
      }
      if (!fileObj.type) {
        this.$message.error('这不是图片')
        return false
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('上传文件过大', file.size)
        return false //必须返回false
      }
      this.fileList.push(file)
      this.uploadUserFace()
    },
    handleChange() {},
    handlePreview() {},
    handleRemove() {},
    async uploadUserFace() {
      const files = new FormData()
      for (let i = 0; i < this.fileList.length; i++) {
        files.append('file', this.fileList[i])
      }
      try {
        const upload = await uploadFile.txUpload(files)
        var layerImg = []
        this.images = upload.data.url
        this.faceIds = upload.data.id
        layerImg.push(this.userfaceUrl + this.images)
        this.fileList = []
        this.layerImg = layerImg
        this.$message.success({
          message: '上传图片成功'
        })
      } catch {
        this.$message.error({
          message: '上传图片失败'
        })
      }
    },
    removeImg({ img, index }) {
      this.layerImg.splice(index, 1)
      this.faceIds = null
      this.images = null
    },
    onCloseUserDialog() {
      this.$emit('onSubmit', false)
    },
    onSubmitUserInfo() {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          this.submitUserForm()
        } else {
          return false
        }
      })
    },
    // 提交form 数据
    async submitUserForm() {
      var userForm
      const loading = this.$loading({
        target: document.querySelector('.el-dialog'),
        lock: true,
        text: 'loading...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      var newUserForm = this.newUserForm
      // newUserForm.icon = this.faceIds.join(',')
      newUserForm.icon = this.images ? this.images : ''

      try {
        if (this.submitText) {
          userForm = await userManage.editUser(newUserForm)
          console.log('edit')
        } else {
          userForm = await userManage.addUser(newUserForm)
          console.log('add')
        }
        loading.close()
        if (userForm.data != null) {
          this.$message.success({
            message: this.submitText ? '修改用户信息成功' : '添加用户信息成功',
            duration: 2000
          })
        } else {
          this.$message.error({
            message: userForm.message,
            duration: 2000
          })
        }
        this.newUserForm = { ...newUserForm }
        this.$emit('onSubmit', true)
      } catch {
        loading.close()
        this.$message.error({
          message: '噢，发现错误，联系后台管理员',
          duration: 2000
        })
        this.newUserForm = { ...newUserForm }
        this.$emit('onSubmit', false)
      }
    }
  }
}
</script>
